package neu.soft.facade;

import lombok.extern.slf4j.Slf4j;
import neu.soft.binder.ChannelBinder;
import neu.soft.constant.PayableOrderType;
import neu.soft.entity.*;
import neu.soft.exception.AppException;
import neu.soft.exception.AppExceptionCodeMsg;
import neu.soft.feignclient.OperationServerFeignClient;
import neu.soft.query.PurchaseOrderQuery;
import neu.soft.service.PayableOrderService;
import neu.soft.service.PurchaseService;
import neu.soft.util.TypeConvert;
import neu.soft.vo.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Slf4j
public class PurchaseOrderMessageHandler {

    @Autowired
    PurchaseService purchaseService;

    @Autowired
    PayableOrderService payableOrderService;

    @Autowired
    OperationServerFeignClient operationServerFeignClient;

    @Autowired
    ChannelBinder channelBinder;

    // 处理业务中心发来的购货单
    public Integer receivePurchaseOrder(OperationPurchaseOrder operationPurchaseOrder) {
        FinancialPurchaseOrder financialPurchaseOrder = TypeConvert.purchaseOrderConverter(operationPurchaseOrder);
        purchaseService.addPurchaseOrder(financialPurchaseOrder);
        List<GoodInfo> goodInfoList = financialPurchaseOrder.getGoodInfoList();
        Integer financialOrderId = financialPurchaseOrder.getFinancialOrderId();
        goodInfoList.forEach(goodInfo -> goodInfo.setGoodOrderId(financialOrderId));
        purchaseService.batchInsertGoodInfo(goodInfoList);
        return financialPurchaseOrder.getFinancialOrderId();
    }

    //接收库房核对入库单以及与入库绑定的购货单的结果
    public void generatePayableOrder(Integer operationOrderId) {
        //生成应付单
        PurchaseOrderQuery purchaseOrderQuery = new PurchaseOrderQuery();
        purchaseOrderQuery.setPurchaseOrderId(operationOrderId);
        PageBean<FinancialPurchaseOrder> pageBean = purchaseService.findByPage(purchaseOrderQuery);
        List<FinancialPurchaseOrder> financialPurchaseOrderList = pageBean.getRowData();
        FinancialPurchaseOrder financialPurchaseOrder = financialPurchaseOrderList.get(0);
        String type = PayableOrderType.UN_PAID.getCode();
        PayableOrder payableOrder = payableOrderService.generate(financialPurchaseOrder, type);
        payableOrderService.addPayableOrder(payableOrder);

    }

    /**
     *     调用模拟供应商接口，模拟供应商往库房发消息，sleep几秒，财务调用接收发票对象，然后调用自身的服务登记发票。
     *     等库房消息到来后，对发票和入库明细进行核算，生成应付单，点击支付，将应付单与发票核算，更新支付单状态，发票类型更改
     * @param financialOrderId
     * @return
     */
    public Map<String,Object> sendVendorInfo(Integer financialOrderId){
        //查询购货单
        FinancialPurchaseOrder financialPurchaseOrder = purchaseService.findById(financialOrderId);
        if (financialPurchaseOrder == null) {
            throw new AppException(AppExceptionCodeMsg.QUERY_FAIL);
        }
        //财务中心购货单的商品列表，绑定的财务中心购货单
        List<GoodInfo> goodInfoList = financialPurchaseOrder.getGoodInfoList();
        //得到商品的id列表
        List<String> goodIdList = goodInfoList.stream().map(GoodInfo::getGoodId).collect(Collectors.toList());
        //查询商品信息集合
        List<Good> goodList = operationServerFeignClient.findGoods(goodIdList);
        if ("-1".equals(goodList.get(0).getGoodId())) {
            throw new AppException(AppExceptionCodeMsg.QUERY_FAIL);
        }
        //将商品代码和计量单位映射成Map
        Map<String,Object> objectMap = goodList.stream().collect(Collectors.toMap(Good::getGoodId,Good::getMeasure));
        //生成InvoiceGoodInfo的集合
        List<InvoiceGoodInfo> invoiceGoodInfoList = goodInfoList.stream().map(goodInfo -> {
            if (!objectMap.containsKey(goodInfo.getGoodId())){
                throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
            }
            String measure = (String) objectMap.get(goodInfo.getGoodId());
            return TypeConvert.goodInfoToInvoiceGoodInfo(goodInfo,measure);
        }).collect(Collectors.toList());
        Map<String,Object> res = new HashMap<>();
        //设置发票商品列表的信息
        res.put("invoiceGoodInfoList",invoiceGoodInfoList);
        String vendorName = financialPurchaseOrder.getVendor();//得到供应商名称
        Vendor vendor = operationServerFeignClient.getByName(vendorName);//得到供应商信息
        String address = vendor.getVendorAddress();//设置地址信息
        String phone = financialPurchaseOrder.getVendorContact();//联系方式
        String loc =  Arrays.toString(address.split("-"));
        res.put("loc",loc);
        res.put("saleName",vendorName);//销售方名称
        res.put("saleAddressAndPhone",loc+" "+phone);//设置地址+电话
        res.put("saleIdentity","123456789");
        res.put("saleAccount","中国银行 "+vendor.getVendorBankAccount());
        res.put("buyName","DNA重组有限公司");
        res.put("buyIdentity","987654321");
        res.put("addressAndPhone","辽宁省沈阳市浑南区创新路195号 024-83687313");
        res.put("account","中国银行 111111111111111");
        res.put("totalPrice",financialPurchaseOrder.getPurchasePrice());
        res.put("orderId",financialOrderId);
        res.put("operationId",financialPurchaseOrder.getPurchaseOrderId());//购货单id给中心库房看
        return res;
    }

}
